import React from 'react';
import { DatePicker } from 'antd';
import moment from 'moment';

import { useTRState } from '#/utils/trHooks';
import { SyncOutlined } from '#/utils/antdIcons';
import Box from '@/pages/GanSuDaTang/Dashboard/components/Box';
import Segmented from '@/pages/GanSuDaTang/Dashboard/components/Segmented';
import { default as MyChart } from '@/pages/GanSuDaTang/Dashboard/components/chart';
import {
  getElectricPriceDistributionChart,
  getMarketTradingDaily,
} from '@/pages/GanSuDaTang/Dashboard/services';
import { titles, dateTypes, getOption } from './helper';
import styles from './index.less';

export default ({ dataSource }) => {
  const [state, setState] = useTRState({
    dd: moment(), // 全省供需默认当日
    mm: moment().add(-1, 'month'), // 电价分布默认上月
    isAll: true, // 是否全省
    dateType: dateTypes[0].value, // 按月/年
    loading: true,
    chart1: null, // 全省供需
    chart2: null, // 电价(月)
    chart3: null, // 电价(年)
  });

  React.useEffect(() => {
    Promise.all([fetch1(), fetch2()]);
  }, []);

  React.useEffect(() => {
    const chart3 = getOption(
      dataSource,
      [{ name: '总', color: '#18A0FB', key: 'price' }],
      '元/MWh',
    );
    setState({ chart3 });
  }, [JSON.stringify(dataSource)]);

  const fetch1 = async () => {
    // 全身供需
    const _date = state.dd.format('YYYY-MM-DD');
    const res = await getMarketTradingDaily(_date);
    const list = Object.values(res?.data?.areaData || {});
    list.map((x, i) => {
      x.id = `${i + 1}`.padStart(2, '0');
      x.curveData = res?.data?.curveData?.[i + 1] || 0;
    });
    const chart1 = getOption(
      list,
      [
        { name: '系统负荷-联络线', color: '#FF0000', key: 'curveData', noArea: true },
        { name: '火电最小', color: '#7f7f7f', key: 'fireMin', stack: 'A' },
        { name: '水电计划', color: '#50ad5c', key: 'hydrolicPlan', stack: 'A' },
        { name: '新能源预测', color: '#bfdde7', key: 'newEnergySourceForecast', stack: 'A' },
        { name: '火电可调', color: '#ffff53', key: 'thermalPowerAdjustable', stack: 'A' },
      ],
      'MW',
    );
    setState({ chart1 });
    return Promise.resolve();
  };

  const fetch2 = async () => {
    // 电价分布(月)
    const _date = state.mm.format('YYYY-MM');
    const res = await getElectricPriceDistributionChart(_date);
    let heDongMap = res?.data?.heDong || {};
    let heXiMap = res?.data?.heXi || {};
    const list = Array.from({ length: 24 }, (__, i) => ({
      id: `${i + 1}`.padStart(2, '0'),
      heDong: heDongMap?.[i + 1] || 0,
      heXi: heXiMap?.[i + 1] || 0,
    }));
    const chart2 = getOption(
      list,
      [
        { name: '河东', color: '#18A0FB', key: 'heDong' },
        { name: '河西', color: '#ED8139', key: 'heXi' },
      ],
      '元/MWh',
    );
    setState({ chart2 });
    return Promise.resolve();
  };

  return (
    <Box
      title={state.isAll ? titles[1] : titles[0]}
      prepend={
        <div className={styles.btn} onClick={() => setState({ isAll: !state.isAll })}>
          <SyncOutlined style={{ fontSize: 14 }} />
          <span>{state.isAll ? titles[0] : titles[1]}</span>
        </div>
      }
      apend={
        !state.isAll ? (
          <Segmented
            value={state.dateType}
            options={dateTypes}
            onChange={(dateType) => setState({ dateType })}
          />
        ) : null
      }
    >
      <div className={styles.container}>
        {state.isAll ? (
          <DatePicker
            value={state.dd}
            onChange={(dd) => {
              state.dd = dd;
              setState({ dd });
              fetch1();
            }}
            className={styles.date}
            style={{ width: 160 }}
            close
            placeholder={'请选择日期'}
            format={'YYYY年MM月DD日'}
            getPopupContainer={(e) => document.getElementById('DaTangDashboard')}
            allowClear={false}
          />
        ) : state.dateType === 'month' ? (
          <DatePicker
            value={state.mm}
            onChange={(mm) => {
              state.mm = mm;
              setState({ mm });
              fetch2();
            }}
            className={styles.date}
            style={{ width: 160 }}
            picker="month"
            placeholder={'请选择日期'}
            format={'YYYY年MM月'}
            getPopupContainer={(e) => document.getElementById('DaTangDashboard')}
            allowClear={false}
          />
        ) : null}
        <MyChart
          option={
            state.isAll ? state.chart1 : state.dateType === 'month' ? state.chart2 : state.chart3
          }
        />
      </div>
    </Box>
  );
};
